#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>

#include "hpcr_types.h"
#include "hpcr_log.h"

// 写入到1号文件描述符中
// 如果要设置日志文件，则只需要关闭1号和2号文件描述符，再打开日志文件即可写入
void hpcr_log(char *message, char *file, int line, hpcr_log_level_t level)
{
    char buffer[_DEFINE_HPCR_LOG_MAX_LEN_];
    buffer[0] = '\0';
    int len = 0;
    switch (level)
    {
    case HPRC_LOG_LEVEL_ERROR:
        sprintf(buffer, "[ERROR] ");
        len = strlen(buffer);
        snprintf(buffer + len, _DEFINE_HPCR_LOG_MAX_LEN_ - len, "%s %s %s:%d %s\n", __DATE__, __TIME__, file, line, message);
        break;
    case HPRC_LOG_LEVEL_INFO:
        /* code */
        snprintf(buffer, _DEFINE_HPCR_LOG_MAX_LEN_, "[INFO] %s %s %s\n", __DATE__, __TIME__, message);
        break;
    case HPRC_LOG_LEVEL_WARNING:
        sprintf(buffer, "[WARNING] ");
        len = strlen(buffer);
        snprintf(buffer + len, _DEFINE_HPCR_LOG_MAX_LEN_ - len, "%s %s %s:%d %s\n", __DATE__, __TIME__, file, line, message);
        break;
    case HPRC_LOG_LEVEL_DEBUG:
        sprintf(buffer, "[DEBUG] ");
        len = strlen(buffer);
        snprintf(buffer + len, _DEFINE_HPCR_LOG_MAX_LEN_ - len, "%s %s %s:%d %s\n", __DATE__, __TIME__, file, line, message);
        break;
    default:
        break;
    }
    write(_DEFINE_HPCR_LOG_OUTPUT_FD_, buffer, strnlen(buffer, _DEFINE_HPCR_LOG_MAX_LEN_));
}